package com.hiwhitley.himei.module.game;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.hiwhitley.himei.R;
import com.hiwhitley.himei.contract.GameDetailContract;
import com.hiwhitley.himei.contract.model.GameDetailModel;
import com.hiwhitley.himei.contract.presenter.GameDetailPresenter;
import com.hiwhitley.himei.entity.Game;
import com.hiwhitley.himei.entity.GameScreenHorizontal;
import com.hiwhitley.himei.entity.GameScreenVertical;
import com.hiwhitley.himei.entity.GameVideoHorizontal;
import com.hiwhitley.himei.entity.GameVideoVertical;
import com.hiwhitley.himei.entity.ScreenItem;
import com.hiwhitley.himei.mvpframe.base.BaseFrameActivity;
import com.hiwhitley.himei.utils.StrUtil;
import com.hiwhitley.himei.utils.ToastUtil;
import com.hiwhitley.himei.widget.DownloadProgressButton;
import com.hiwhitley.himei.widget.glide.GlideImageView;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.GSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;
import zlc.season.rxdownload2.function.Utils;

import static android.os.Environment.DIRECTORY_DOWNLOADS;

/**
 * Created by hiwhitley on 2016/10/13.
 */

public class GameDetailActivity extends BaseFrameActivity<GameDetailPresenter, GameDetailModel> implements GameDetailContract.View {


    private static final String TAG_GID = "gid";
    private static final String TAG_GAME_NAME = "gameName";

    @BindView(R.id.game_icon)
    GlideImageView mGameIcon;
    @BindView(R.id.game_tags)
    TextView mGameTags;
    @BindView(R.id.referrer_avatar)
    GlideImageView mReferrerAvatar;
    @BindView(R.id.nickname)
    TextView mNickname;
    @BindView(R.id.user_share)
    TextView mUserShare;
    @BindView(R.id.tv_intro)
    TextView mTvIntro;
    @BindView(R.id.tv_share)
    TextView mTvShare;
    @BindView(R.id.rl_detail)
    CardView mRlDetail;
    @BindView(R.id.rv_images)
    RecyclerView mImagesRecyclerView;
    @BindView(R.id.download_button)
    DownloadProgressButton downloadButton;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.collapsing_toolbar_layout)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.tv_advice)
    TextView mTvAdvice;
    @BindView(R.id.tv_version_name)
    TextView mTvVersionName;
    @BindView(R.id.tv_size)
    TextView mTvSize;
    @BindView(R.id.tv_developer)
    TextView mTvDeveloper;
    @BindView(R.id.tv_lang)
    TextView mTvLang;
    @BindView(R.id.tv_download_count)
    TextView mTvDownloadCount;
    @BindView(R.id.tv_update_time)
    TextView mTvUpdateTime;

    private Game game;
    private RxDownload mRxDownload;
    private Disposable mDisposable;
    private String url;
    private int lastProgress = 0;
    final String defaultPath = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).getPath();
    private MultiTypeAdapter mMultiTypeAdapter;

    public static Intent newIntent(Context context, int gid, String gameName) {
        Intent intent = new Intent(context, GameDetailActivity.class);
        intent.putExtra(TAG_GID, gid);
        intent.putExtra(TAG_GAME_NAME, gameName);
        return intent;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_game_detail;
    }

    @Override
    protected void init() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        collapsingToolbarLayout.setTitle(getIntent().getStringExtra(TAG_GAME_NAME));
        collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.START);
        int gid = getIntent().getIntExtra(TAG_GID, 0);

        mPresenter.loadGameDetail(gid);
        mRxDownload = RxDownload.getInstance();

        mMultiTypeAdapter = new MultiTypeAdapter();
        mMultiTypeAdapter.register(GameScreenHorizontal.class, new GameScreenHorizontalViewProvider());
        mMultiTypeAdapter.register(GameScreenVertical.class, new GameScreenVerticalViewProvider());
        mMultiTypeAdapter.register(GameVideoHorizontal.class, new GameVideoHorizontalViewProvider());
        mMultiTypeAdapter.register(GameVideoVertical.class, new GameVideoVerticalViewProvider());

        mImagesRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mImagesRecyclerView.setAdapter(mMultiTypeAdapter);
    }

    //设置建议，下载量等信息
    private void initGameDetail() {
        mTvAdvice.setText(game.getAdvice());
        mTvVersionName.setText(game.getPacks().get(0).getVersion_name());
        mTvSize.setText(game.getPacks().get(0).getSize() / 1024 / 1024 + "MB");
        mTvDeveloper.setText(game.getDeveloper());
        mTvLang.setText(game.getPacks().get(0).getLang());
        mTvDownloadCount.setText(game.getDownload_count() + "");
        mTvUpdateTime.setText(game.getPacks().get(0).getUpdated_at() == 0 ?
                "无" : StrUtil.timeStamp2Date(game.getPacks().get(0).getUpdated_at() + ""));
    }

    @Override
    protected void setListeners() {
        downloadButton.setCurrentText("下载");
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downloadButton.getState() == DownloadProgressButton.STATE_NORMAL || downloadButton.getState() == DownloadProgressButton.STATE_PAUSE) {
                    toDownloadApk();
                }
                if (downloadButton.getState() == DownloadProgressButton.STATE_DOWNLOADING) {
                    downloadButton.setState(DownloadProgressButton.STATE_PAUSE);
                    downloadButton.setCurrentText("继续");
                    pause();
                }
                if (downloadButton.getState() == DownloadProgressButton.STATE_FINISH) {
                    installApk();
                }
            }
        });
    }

    private void toDownloadApk() {
        start();
    }

    @Override
    public void showGameDetail(Game game) {
        this.game = game;
        this.url = game.getPacks().get(0).getDownload_url();
        showCovers();
        showGameDesc();
        initGameDetail();
    }

    @Override
    public void showGameScreens(List<ScreenItem> screenItemList) {

        mMultiTypeAdapter.setItems(screenItemList);
        mMultiTypeAdapter.notifyDataSetChanged();

    }


    private void showCovers() {

        mGameIcon.loadNetRoundedCornersImage(game.getIcon().getUrl(), R.drawable.bg_holder_brown);
        mGameTags.setText(game.getTags().toString());
        mTvShare.setText(game.getShare());

    }

    private void showGameDesc() {
        if (game.getReferrer() == null) {
            mNickname.setText(game.getEditor().getNickname());
            mReferrerAvatar.loadNetCircleImage(game.getEditor().getAvatar(), R.drawable.bg_holder_brown);
        } else {
            mNickname.setText(game.getReferrer().getNickname());
            mReferrerAvatar.loadNetCircleImage(game.getReferrer().getAvatar(), R.drawable.bg_holder_brown);
        }
        mUserShare.setText(game.getEditor_words());
        mTvIntro.setText(Html.fromHtml(game.getIntro()));

    }

    @Override
    public void onRequestStart() {

    }

    @Override
    public void onRequestEnd() {

    }

    @Override
    public void onBackPressed() {
        if (StandardGSYVideoPlayer.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
        pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoPlayer.releaseAllVideos();
        destroy();
    }

    private void start() {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .doOnNext(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (!granted) {
                            ToastUtil.show("您已禁止了写数据权限");
                            throw new RuntimeException("no permission");
                        }
                    }
                })
                .observeOn(Schedulers.io())
                .compose(mRxDownload.<Boolean>transform(url, game.getName_en() + ".apk", defaultPath))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<DownloadStatus>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(DownloadStatus value) {
                        float progressF = (float) (value.getDownloadSize() * 1.0 / value.getTotalSize());
                        int progressI = (int) (progressF * 100);
                        Log.i("download", "progressI" + progressI);
                        if (progressI > lastProgress) {
                            lastProgress = progressI;
                            downloadButton.setState(DownloadProgressButton.STATE_DOWNLOADING);
                            downloadButton.setProgressText("正在下载", progressI);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        downloadButton.setState(DownloadProgressButton.STATE_FINISH);
                        downloadButton.setCurrentText("安装中");
                        installApk();
                    }
                });
    }

    private void pause() {
        Utils.dispose(mDisposable);
    }

    private void destroy() {
        Utils.dispose(mDisposable);
    }

    private void installApk() {
        Uri uri = Uri.fromFile(new File(defaultPath + File.separator + game.getName_en() + ".apk"));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
